# views/favorites.py

import os
import shutil
import logging
from PyQt5.QtWidgets import (
    QWidget, QLabel, QPushButton, QHBoxLayout, QVBoxLayout, QFileDialog,
    QSlider, QGridLayout, QScrollArea, QMessageBox, QMenu
)
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt, pyqtSignal
from utils.image_utils import ImageUtils

# 定义一个可处理右键事件的 QLabel 子类
class ClickableLabel(QLabel):
    # 定义两个信号，传递图像路径
    remove_favorite_requested = pyqtSignal(str)
    open_image_requested = pyqtSignal(str)

    def __init__(self, image_path, parent=None):
        super().__init__(parent)
        self.image_path = image_path  # 存储图像路径

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        remove_action = menu.addAction("取消收藏")
        open_action = menu.addAction("打开")
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == remove_action:
            # 发射信号，传递图像路径
            self.remove_favorite_requested.emit(self.image_path)
        elif action == open_action:
            # 发射信号，传递图像路径
            self.open_image_requested.emit(self.image_path)

class Favorites(QWidget):
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window

        # 初始化变量
        self.image_files = list(self.main_window.favorites)
        self.thumbnail_size = 200  # 增大默认缩略图大小
        self.image_labels = {}  # 用于存储图像路径到 QLabel 的映射

        # 图像处理工具
        self.image_utils = ImageUtils(self.thumbnail_size)
        self.image_utils.thumbnail_ready.connect(self.on_thumbnail_ready)

        # 创建控件
        self.create_widgets()

    def create_widgets(self):
        layout = QVBoxLayout(self)

        # 导出按钮和缩略图大小调整滑块
        top_layout = QHBoxLayout()

        export_button = QPushButton("导出全部收藏")
        export_button.clicked.connect(self.export_favorites)
        top_layout.addWidget(export_button)

        size_label = QLabel("缩略图大小")
        top_layout.addWidget(size_label)

        self.thumbnail_size_slider = QSlider(Qt.Horizontal)
        self.thumbnail_size_slider.setMinimum(150)  # 增大最小值
        self.thumbnail_size_slider.setMaximum(600)  # 增大最大值
        self.thumbnail_size_slider.setValue(self.thumbnail_size)
        self.thumbnail_size_slider.valueChanged.connect(self.on_thumbnail_size_change)
        top_layout.addWidget(self.thumbnail_size_slider)

        # 放大缩小按钮
        zoom_in_button = QPushButton("放大")
        zoom_in_button.clicked.connect(self.zoom_in)
        top_layout.addWidget(zoom_in_button)

        zoom_out_button = QPushButton("缩小")
        zoom_out_button.clicked.connect(self.zoom_out)
        top_layout.addWidget(zoom_out_button)

        top_layout.addStretch()
        layout.addLayout(top_layout)

        # 滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_content = QWidget()
        self.grid_layout = QGridLayout(self.scroll_content)
        self.scroll_area.setWidget(self.scroll_content)

        layout.addWidget(self.scroll_area)

        # 显示占位符
        self.display_placeholder()

    def load_favorites(self):
        self.image_files = list(self.main_window.favorites)
        self.update_favorites_view()
        logging.info("加载收藏视图。")

    def update_favorites_view(self):
        # 清空原有内容
        for i in reversed(range(self.grid_layout.count())):
            widget_to_remove = self.grid_layout.itemAt(i).widget()
            self.grid_layout.removeWidget(widget_to_remove)
            widget_to_remove.setParent(None)
        self.image_labels.clear()

        if not self.image_files:
            self.display_placeholder()
            return

        thumbnails_per_row = self.calculate_thumbnails_per_row()
        for idx, image_path in enumerate(self.image_files):
            row = idx // thumbnails_per_row
            col = idx % thumbnails_per_row

            # 使用 ClickableLabel 替代 QLabel
            thumbnail_label = ClickableLabel(image_path, self)
            thumbnail_label.setFixedSize(self.thumbnail_size, self.thumbnail_size)
            thumbnail_label.setAlignment(Qt.AlignCenter)
            thumbnail_label.setStyleSheet("border: 1px solid gray;")
            thumbnail_label.setText("加载中...")

            # 连接信号到槽函数
            thumbnail_label.remove_favorite_requested.connect(self.remove_favorite)
            thumbnail_label.open_image_requested.connect(self.open_image)

            self.grid_layout.addWidget(thumbnail_label, row, col)

            # 存储映射
            self.image_labels[image_path] = thumbnail_label

            # 异步加载缩略图
            self.image_utils.generate_thumbnail(image_path)

    def calculate_thumbnails_per_row(self):
        gallery_width = self.scroll_area.width()
        thumbnails_per_row = max(1, gallery_width // (self.thumbnail_size + 20))
        return thumbnails_per_row

    def on_thumbnail_size_change(self, value):
        self.thumbnail_size = value
        self.image_utils.thumbnail_size = self.thumbnail_size
        self.image_utils.cache.clear()
        self.update_favorites_view()
        logging.info(f"收藏缩略图大小调整为：{self.thumbnail_size}")

    def zoom_in(self):
        self.thumbnail_size += 10
        if self.thumbnail_size > 800:
            self.thumbnail_size = 800
        self.thumbnail_size_slider.setValue(self.thumbnail_size)
        self.main_window.viewer.thumbnail_size = self.thumbnail_size
        logging.info(f"收藏缩放放大，当前缩略图大小：{self.thumbnail_size}")

    def zoom_out(self):
        self.thumbnail_size -= 10
        if self.thumbnail_size < 200:
            self.thumbnail_size = 200
        self.thumbnail_size_slider.setValue(self.thumbnail_size)
        self.main_window.viewer.thumbnail_size = self.thumbnail_size
        logging.info(f"收藏缩放缩小，当前缩略图大小：{self.thumbnail_size}")

    def on_thumbnail_ready(self, image_path, pixmap):
        # 根据图像路径找到对应的 QLabel 并设置缩略图
        if image_path in self.image_labels:
            label = self.image_labels[image_path]
            label.setPixmap(pixmap.scaled(
                self.thumbnail_size, self.thumbnail_size, Qt.KeepAspectRatio, Qt.SmoothTransformation))
            label.setText("")  # 清除加载中...
            logging.info(f"收藏缩略图已加载：{image_path}")

    def select_image_from_favorites(self, image_path):
        if image_path in self.image_files:
            self.main_window.viewer.current_index = self.image_files.index(image_path)
            self.main_window.viewer.update_image()
            self.main_window.tab_widget.setCurrentWidget(self.main_window.viewer)
            logging.info(f"从收藏中选择并显示图片：{image_path}")

    def export_favorites(self):
        export_directory = QFileDialog.getExistingDirectory(self, "选择导出目录")
        if not export_directory:
            logging.info("用户取消导出收藏。")
            return
        exported_count = 0
        for favorite in self.image_files:
            if os.path.isfile(favorite):
                filename = os.path.basename(favorite)
                destination = os.path.join(export_directory, filename)
                try:
                    shutil.copy2(favorite, destination)
                    exported_count += 1
                except Exception as e:
                    QMessageBox.critical(self, "导出错误", f"复制 {filename} 失败：\n{e}")
                    logging.error(f"复制 {filename} 失败：{e}")
        QMessageBox.information(self, "导出完成", f"已导出 {exported_count} 张收藏的图片到：\n{export_directory}")
        logging.info(f"已导出 {exported_count} 张收藏的图片到：{export_directory}")

    def remove_favorite(self, image_path):
        """取消收藏指定的图片"""
        logging.info(f"尝试取消收藏图片：{image_path}")
        if image_path in self.main_window.favorites:
            self.main_window.favorites.remove(image_path)
            self.main_window.save_settings()
            self.load_favorites()  # 重新加载收藏视图
            logging.info(f"已取消收藏图片：{image_path}")

    def open_image(self, image_path):
        """在图片查看界面打开指定的图片"""
        logging.info(f"打开收藏中的图片：{image_path}")
        if image_path in self.main_window.viewer.image_files:
            self.main_window.viewer.current_index = self.main_window.viewer.image_files.index(image_path)
            self.main_window.viewer.update_image()
            self.main_window.tab_widget.setCurrentWidget(self.main_window.viewer)
            logging.info(f"已在图片查看窗口中打开图片：{image_path}")

    def display_placeholder(self):
        # 清空原有内容
        for i in reversed(range(self.grid_layout.count())):
            widget_to_remove = self.grid_layout.itemAt(i).widget()
            self.grid_layout.removeWidget(widget_to_remove)
            widget_to_remove.setParent(None)
        placeholder_label = QLabel("暂无收藏")
        placeholder_label.setAlignment(Qt.AlignCenter)
        self.grid_layout.addWidget(placeholder_label, 0, 0)
        logging.info("收藏视图显示占位符：暂无收藏。")

    def resizeEvent(self, event):
        self.update_favorites_view()
        super().resizeEvent(event)
